<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import confVue from "./conf.vue";
import store from "../store/index";

var CancelToken = axios.CancelToken;
var source = CancelToken.source();
// let version = 1.0;
let lan = localStorage.getItem("key_language");
///设置版本
// function setVersion(_version) {
//   if (_version !== undefined && _version !== "" && _version !== null)
//     // version = _version;
// }
///创建带token的请求
function request(paramerter) {
  var axios_instance = axios.create({
    // config里面有这个transformRquest， 这个选项会在发送参数前进行处理。 这时候我们通过Qs.stringify转换为表单查询参数
    transformRequest: [
      function(data) {
        if (paramerter.contentType === "application/json") {
          if (data != null && data != undefined) {
            data = JSON.stringify(data);
            return data;
          }
        } else return data;
      },
    ],
    // 设置Content - Type
    headers: {
      "Content-Type": paramerter.contentType,
      "Data-Type": paramerter.dataType,
      Authorization: "Bearer " + window.localStorage.getItem("gloabl_token"),
      // "api-version": version,
      language: lan,
      grant_type: localStorage.getItem("grant_type") || "",
    },
    cancelToken: source.token,
  });
  return axios_instance;
}

///将返回参数封装完成
function CommPromise(res) {
  return new Promise((resolve, reject) => {
    res.then(
      (response) => {
        if (response.data.status) {
          store.state.unAuth = false;
          resolve(response.data);
        } else {
          if (response.data.code == 4011) {
            if (!store.state.unAuth) {
              ElMessage({
                showClose: true,
                message: response.data.message,
                type: "error",
              });
              setTimeout(() => {
                window.location.href = "/";
              }, 500);
            }
          } else {
            store.state.unAuth = false;
            resolve(response.data);
          }
        }
      },
      (err) => {
        if (err && err.response) {
          $AlertErrorr(err.response);
          setTimeout(() => {
            if (err.response.status == 401) {
              if (!store.state.unAuth) {
                store.state.unAuth = true;
                window.location.href = "/login";
              }
            }
          }, 500);
          if (axios.isCancel(err)) {
            store.state.unAuth = false;
            // 取消请求的情况下，终端Promise调用链
            return new Promise(() => {});
          } else {
            store.state.unAuth = false;
            reject(err.response);
          }
        } else {
          store.state.unAuth = false;
          ElMessage({
            showClose: true,
            message: "接口内部服务错误",
            type: "error",
          });
        }
      }
    );
  });
}
///将返回参数封装完成
function CommDownloadPromise(res, filename) {
  res.then(
    (response) => {
      if (response.status) {
        const data = response.data;
        let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.href = url;
        a.download = filename; //这里后台写什么后缀名格式，你就写什么
        a.click(); // 模拟点击下载
        window.URL.revokeObjectURL(url);
      } else {
        ElMessage({
          showClose: true,
          message: response.data.message,
          type: "error",
        });
      }
    },
    (err) => {
      if (err && err.response) {
        $AlertErrorr(err.response);
        setTimeout(() => {
          if (err.response.status == 401) {
            source.cancel();
            window.location.href = "/login";
          }
        }, 500);
      } else {
        ElMessage({
          showClose: true,
          message: "接口内部服务错误",
          type: "error",
        });
      }
    }
  );
}
///封装错误信息
function $AlertErrorr(response) {
  let statusText = "";
  // 1.公共错误处理
  // 2.根据响应码具体处理
  switch (response.status) {
    case 400:
      statusText = "请求失败，参数错误";
      break;
    case 401:
      statusText = "未授权，请重新登录";
      break;
    case 403:
      statusText = "拒绝访问";
      break;
    case 404:
      statusText = "请求错误,未找到该资源";
      break;
    case 405:
      statusText = "请求方法未允许";
      break;
    case 415:
      statusText = "请求数据类型错误";
      break;
    case 408:
      statusText = "请求超时";
      break;
    case 500:
      statusText = Setting500Error(response.data);
      break;
    case 501:
      statusText = "网络未实现";
      break;
    case 502:
      statusText = "网络错误";
      break;
    case 503:
      statusText = "服务不可用";
      break;
    case 504:
      statusText = "网络超时";
      break;
    case 505:
      statusText = "http版本不支持该请求";
      break;
    default:
      statusText = `连接错误:${response.statusText}`;
  }
  ElMessage({
    showClose: true,
    message: statusText,
    type: "error",
  });
}
function Setting500Error(res) {
  return res.message == "" || res.message == null
    ? "内部服务器错误"
    : res.message;
}
///将返回参数封装完成
function CommAllPromise(request) {
  return new Promise((resolve, reject) => {
    axios.all(request).then(
      axios.spread(function(...res) {
        let resAry = res.filter((o) => o.status !== 200);
        if (resAry.length > 0) {
          $AlertErrorr(resAry[0]);
        } else {
          let reponAry = res.filter((o) => !o.data.status);
          if (reponAry.length > 0) {
            ElMessage({
              showClose: true,
              message: !reponAry[0].data.message,
              type: "error",
            });
            setTimeout(() => {
              if (!res[0].data.code == 4011) {
                window.location.href = "/";
              }
            }, 500);
          } else {
            resolve(res);
          }
        }
      }),
      (err) => {
        if (err && err.response) {
          $AlertErrorr(err.response);
          setTimeout(() => {
            if (err.response.status == 401) {
              if (!store.state.unAuth) {
                store.state.unAuth = true;
                window.location.href = "/login";
              }
            } else {
              store.state.unAuth = false;
            }
          }, 500);
          reject(err.response);
        } else {
          store.state.unAuth = false;
          ElMessage({
            showClose: true,
            message: "接口内部服务错误",
            type: "error",
          });
        }
      }
    );
  });
}
export default {
  //$SetVersion: (_version) => setVersion(_version),
  $All: function(parameters) {
    if (parameters.length > 0) {
      let requts = [];
      parameters.forEach((element) => {
        element.contentType = element.contentType ?? "application/json";
        element.dataType = element.dataType ?? "json";
        var post = request(element);
        var res = post({
          url: confVue.$interfaceApi + element.url,
          method: "POST",
          data: element.model,
        });
        requts.push(res);
      });
      return CommAllPromise(requts);
    }
  },
  ///POST数据请求
  $Post: function(model, url, wayType, contentType, dataType) {
    ///初始化请求
    var paramerter = new Object();
    paramerter.contentType = contentType ?? "application/json";
    paramerter.dataType = dataType ?? "json";
    var post = request(paramerter);
    var res = post({
      url: confVue.$interfaceApi + (wayType ?? confVue.$busApi) + "/" + url,
      method: "POST",
      data: model,
    });
    return CommPromise(res);
  },
  ///Get数据请求
  $Get: function(model, url, wayType, contentType, dataType) {
    ///初始化请求
    var paramerter = new Object();
    paramerter.contentType = contentType ?? "application/json";
    paramerter.dataType = dataType ?? "json";
    var get = request(paramerter);
    var res = get({
      url: confVue.$interfaceApi + (wayType ?? confVue.$busApi) + "/" + url,
      method: "GET",
      data: model ?? "",
    });
    return CommPromise(res);
  },
  ///删除数据请求
  $Delete: function(model, url, wayType) {
    ///初始化请求
    var paramerter = new Object();
    paramerter.contentType = "application/json";
    paramerter.dataType = "json";
    var dl = request(paramerter);
    var res = dl({
      url: confVue.$interfaceApi + (wayType ?? confVue.$busApi) + "/" + url,
      method: "DELETE",
      data: model ?? "",
    });
    return CommPromise(res);
  },
  ///删除数据请求
  $Put: function(model, url, wayType, contentType, dataType) {
    ///初始化请求
    var paramerter = new Object();
    paramerter.contentType = contentType ?? "application/json";
    paramerter.dataType = dataType ?? "json";
    var put = request(paramerter);
    var res = put({
      url: confVue.$interfaceApi + (wayType ?? confVue.$busApi) + "/" + url,
      method: "PUT",
      data: model ?? "",
    });
    return CommPromise(res);
  }, ///POST数据请求
  $download: function(model, url, filename) {
    ///初始化请求
    var paramerter = new Object();
    paramerter.contentType = "application/json";
    paramerter.dataType = "json";
    var post = request(paramerter);
    var res = post({
      url: confVue.$interfaceApi + confVue.$docApi + "/" + url,
      method: "POST",
      data: model,
      responseType: "blob", // 设置响应数据类型
    });
    return CommDownloadPromise(res, filename);
  },
};
</script>
